<template>
    <view
            @touchstart="onTouchStart"
            @touchmove="onTouchMove"
            @touchend="onTouchEnd">
        <slot></slot>
    </view>
</template>

<script>
    export default {
        name: "touch-listen",
        props: {
            min: {
                type: Number,
                default: 50
            }
        },
        data() {
            return {
                touchStartX: 0,
                touchStartY: 0,
                touchEndX: 0,
                touchEndY: 0,
            }
        },
        methods: {
            onTouchStart(e) {
                this.touchStartX = e.touches[0].pageX;
                this.touchStartY = e.touches[0].pageY;
            },
            onTouchEnd() {
                const moveX = this.touchEndX - this.touchStartX;
                const moveY = this.touchEndY - this.touchStartY;
                if (Math.abs(moveY) > Math.abs(moveX)) {
                    if (moveY > this.min) {
                        this.$emit('down');
                        this.$emit('move', 'down');

                    } else if (moveY < -this.min) {
                        this.$emit('up');
                        this.$emit('move', 'up');
                    }
                } else {
                    if (moveX > this.min) {
                        this.$emit('right');
                        this.$emit('move', 'right');
                    } else if (moveX < -this.min) {
                        this.$emit('left');
                        this.$emit('move', 'left');
                    }
                }
            },
            onTouchMove(e) {
                this.touchEndX = e.touches[0].pageX;
                this.touchEndY = e.touches[0].pageY;
            },
        }
    }
</script>

<style scoped lang="less">
</style>
